import { makeAutoObservable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';
import { Message } from '@alifd/next';

export default class OrderStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  modal = [];
  members = [];
  loading = false;
  skip = false; // 是否从成员列表进入订单

  _orderStatus = '1';
  _tab_status = '1';

  _tabItems = [
    { key: '1', label: t`发布中` },
    { key: '2', label: t`已接单` },
    { key: '3', label: t`已上客` },
    { key: '4', label: t`待打单` },
    { key: '5', label: t`已完成` },
    { key: '-1', label: t`已失效` },
    { key: '0', label: t`已取消` },
    { key: '9', label: t`全部` },
  ];

  allStatuses = [-1, 0, 1, 2, 3, 4, 5];
  partialStatuses = [2, 3, 4, 5];

  // 聊天消息
  _args_chat = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['ts;asc'],
      size: 999,
    },
  };
  total_chat = 0;
  data_chat = [];
  loading_chat = false;

  constructor(rootStore, _orderStatusSearch) {
    this.rootStore = rootStore;
    this._orderStatusSearch = _orderStatusSearch;
    makeAutoObservable(this, { rootStore: false, _orderStatusSearch: true });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    const { orderStatus } = search;
    if (this._orderStatus == '9' && !orderStatus) {
      search.orderStatus = this.skip ? this.partialStatuses : this.allStatuses;
    } else if (this._orderStatus == '9' && orderStatus) {
      search.orderStatus = orderStatus;
    } else {
      search.orderStatus = orderStatus || [this._orderStatus];
    }
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.data = yield api.search({ search, pg });
    } catch (error) {
      Message.error({ content: t`请求列表失败：${error}` });
      throw error;
    } finally {
      this.loading = false;
    }
  }

  * query_chat(pgInfo) {
    _.mergeWith(this._args_chat.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args_chat);
    if (!pg.sort?.length) delete pg.sort;
    this.loading_chat = true;
    try {
      this.total_chat = yield api.count_chat({ search });
      this.data_chat = yield api.search_chat({ search, pg });
    } finally {
      this.loading_chat = false;
    }
  }

  * getLogs(args) {
    const res = yield api.getLogs(args);
    return res;
  }

  * getLogsCount(args) {
    const res = yield api.getLogsCount(args);
    return res;
  }

  * getComments(args) {
    const res = yield api.getComments(args);
    return res;
  }

  * get(id) {
    return yield api.get(id);
  }

  * update(args) {
    yield api.update(args);
    yield this.query();
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  idx_chat(i) {
    return this._args_chat.pg.page * this._args_chat.pg.size + i + 1;
  }

  _findDriver(obj, arr) {
    if (!arr || arr.length == 0) {
      return;
    }
    const data = _.cloneDeep(arr);
    const filterData = data.filter((p) => (p.status !== '0') && (p.status !== '-1'));
    if (filterData.length > 0) {
      const { driverId, driverName, driverPhone, status, takeOrderTime } = filterData[0];
      _.assign(obj, {
        'auxOrder.auxTask.driverInfos.driverId': driverId,
        'auxOrder.auxTask.driverInfos.driverName': driverName,
        'auxOrder.auxTask.driverInfos.driverPhone': driverPhone,
        'auxOrder.auxTask.driverInfos.status': status,
        'auxOrder.auxTask.driverInfos.takeOrderTime': takeOrderTime,
      });
    }
  }

  _table_driver(arr) {
    if (!arr || arr.length == 0) {
      return;
    }
    let obj = {};
    const data = _.cloneDeep(arr);
    const filterData = data.filter(({ status }) => (status !== '0') && (status !== '-1'));
    if (filterData.length > 0) {
      obj = filterData[0];
    }
    return obj;
  }

  _copy_itinerary(info) {
    const { auxOrder } = toJS(info);
    const {
      name = t`无`,
      mainPhone = '',
      hkPhone = '',
      mainlandLicense = t`无`,
      hkLicense = t`无`,
      vehicleModel = t`无`,
      passengerCapacity = '',
    } = auxOrder?.auxTask?.dispatchInformation || {};
    const text =
      `
服务司机：${name},
大陆电话：+86 ${mainPhone},
香港电话：+852 ${hkPhone},
大陆车牌：${mainlandLicense},
香港车牌：${hkLicense},
车辆型号：${vehicleModel},
乘坐人数：${passengerCapacity} 人,`;
    return text;
  }

  async getRooms(args) {
    try {
      return await api.getRooms(args);
    } catch (error) {
      console.log('🚀 _ file: OrderStore.js:182 _ OrderStore _ error:', error);
    }
  }

  async cancelOrderIssue(args) {
    await api.cancelOrderIssue(args);
    this.query();
  }

  async intervention(args) {
    await api.intervention(args);
    this.query();
  }

  * getMember(args) {
    const res = yield api.getMember(args);
    this.members = res.map((p) => ({
      ...p,
      label: `${p.memberId}-${p.nickname}`,
      value: p.phone,
    }));
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get pg_chat() {
    return this._args_chat.pg;
  }

  set pg_chat(pg) {
    this.query_chat({ ...pg });
  }

  get search_chat() {
    this._args_chat.pg.page = 0;
    return this._args_chat.search;
  }

  set search_chat(search) {
    this._args_chat.pg.page = 0;
    this._args_chat.search = search;
    this.query_chat({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  get orderStatus() {
    return this._orderStatus;
  }

  set orderStatus(value) {
    this._orderStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get tab_Status() {
    return this._tab_status;
  }

  set tab_Status(value) {
    this._tab_status = value;
  }
}
